﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;

namespace OfficeExport
{
    public class WordExportor:IExportor
    {
        #region Ctor

        public WordExportor()
        {
            Application = new Word.ApplicationClass();
        }

        #endregion

        #region Properties

        public Word.Application Application
        {
            get;
            protected set;
        }

        #endregion

        #region IExportor Interface

        public void ExportTo(string fileFullName, ExportType exportType)
        {
            int index = fileFullName.LastIndexOf(".");
            if (index > -1)
            {
                string exportFullName = fileFullName.Substring(0, index) + ExportorFactory.GetExportFileExtension(exportType);
                ExportTo(fileFullName, exportFullName, exportType);
            }
        }

        public void ExportTo(string fileFullName, string exportFullName, ExportType exportType)
        {
            Word.Document doc = null;
            try
            {
                int index = fileFullName.LastIndexOf(".");
                string fileExtension = fileFullName.Substring(index, fileFullName.Length - index);
                object openFileName = fileFullName;
                object openFileFormat = ExportorFactory.GetOpenFileFormat<WordExportor>(fileExtension);
                object openMissing = Type.Missing;
                doc = Application.Documents.Open(ref openFileName, ref openMissing, ref openMissing, ref openMissing, ref openMissing, ref openMissing,
                        ref openMissing, ref openMissing, ref openMissing, ref openFileFormat, ref openMissing, ref openMissing, ref openMissing, ref openMissing, ref openMissing, ref openMissing);

                if (doc != null)
                {
                    string exportFileName = fileFullName.Substring(0, index) + ExportorFactory.GetExportFileExtension(exportType);
                    Word.WdExportFormat exportFileForamt = (Word.WdExportFormat)ExportorFactory.GetExportFormat<WordExportor>(exportType);
                    object saveMissing = Type.Missing;
                    doc.ExportAsFixedFormat(exportFileName, exportFileForamt);
                    doc.Close();
                }
            }
            catch (Exception error)
            {
            }
            finally
            {
                if (doc != null)
                {
                    Marshal.ReleaseComObject(doc);
                    GC.Collect();
                }
            }
        }

        public void Dispose()
        {
            Marshal.ReleaseComObject(Application);
            GC.Collect();
        }
        #endregion
    }
}
